# @File    : cycle_ota.py
# @Project : JBL_Android&iOS
from airtest.core.error import TargetNotFoundError
from airtest.core.api import *
from exception.custom_exception import ElectricException
from iOS.normal_ota import NormalOta
import logging
from common.logUtil import info_i, warning_i
logging.getLogger("airtest").setLevel(logging.CRITICAL)


class CycleOta(NormalOta):

    # 循环升级版本号
    c_version = NormalOta.location.read_yaml()['c_version']
    s_c_version = NormalOta.location.read_yaml()['s_c_version']
    test_device = NormalOta.location.read_yaml()['device']
    success = "更新成功.*"

    def cycle_ota(self, num):
        self.check_is_local_ota()
        version = self.check_version()
        for i in range(1, int(num)+1):
            try:
                start_time = time.time()
                if i == 1:
                    self.select_version(version, self.test_device)
                self.ota_start(i, version)
                self.ota_process(i, version)
                if self.test_device == "耳机":
                    version = self.poco(nameMatches=f"{self.earbud}").get_name()[3:]
                else:
                    version = self.poco(nameMatches=f"{self.case}").get_name()[4:]
                end_time = time.time()
                total_time = end_time - start_time
                minutes, seconds = divmod(total_time, 60)
                info_i(f"第 {i} 次升级耗时: {int(minutes)} 分 {int(seconds)} 秒")
            except ElectricException:
                self.fail_num += 1
                self.fail_list.append(i)
                warning_i(f"第 {i} 次升级时耳机电量过低，无法升级!")
                break
            except TargetNotFoundError:
                self.fail_num += 1
                self.fail_list.append(i)
                warning_i("出现异常了，请手动跟换安装包或者出现运行程序")
                break
        sleep(2)
        info_i(f"测试完成, 共压测 {i} 次, 其中 PASS {self.pass_num} 次, FAIL {self.fail_num} 次, FAIL的轮数为{self.fail_list}")
        self.fail_list.clear()

    def select_version(self, version, test_device):
        self.c.connect_windows()
        self.s.select_version(self.s_c_version, test_device)
        self.c.connect_ios()

    def ota_start(self, i, version):
        if self.test_device == "耳机":
            self.poco("软件").click()
        else:
            self.poco("智能保护盒").click()
        self.poco("更新").refresh()
        self.poco("更新").click()
        if version == self.c_version:
            info_i(f"第 {i} 次循环升级开始...")

    # 升级过程
    def ota_process(self, i, version):
        while True:
            if self.poco(nameMatches=f"{self.schedule}").exists():
                while True:
                    if self.poco("耳机电量需超过 50%。").exists():
                        raise ElectricException
                    if not self.poco(nameMatches=f"{self.schedule}").exists():
                        if self.poco(nameMatches=f"{self.success}").exists():
                            self.poco("完成").click()
                            if self.test_device == "耳机":
                                version = self.poco(nameMatches=f"{self.earbud}").get_name()[3:]
                            else:
                                version = self.poco(nameMatches=f"{self.case}").get_name()[4:]
                            self.check_after_version(i, version)
                            break
                        # 更新失败处理
                        elif self.poco("更新失败").exists():
                            self.poco("取消").click()
                            sleep(2)
                            # version = self.ex.check_fail()
                            self.check_after_version(i, version)
                            self.fail_num += 1
                            self.fail_list.append(i)
                            break
                break
            if self.poco("重试").exists():
                warning_i("请将充电盒靠近手机后重试")
                self.poco("重试").click()
                sleep(1)
                self.poco("更新").click()

    # 根据升级后的版本来进行后续操作
    def check_after_version(self, i, version):
        if version == self.c_version:
            info_i(f"第 {i} 次循环成功...")
            sleep(2)
            info_i(f"第 {i} 次循环升级后的版本为: {version}")
            self.pass_num += 1

